<?php
/**
 * 库存操作
 */

namespace app\common\service;

use app\common\model\AgentShop;
use app\common\model\AgentStock;
use app\common\model\AgentStockRecord;
use think\Db;
use think\Exception;

class StockService extends Server {
	
	/**
	 * 改变库存
	 * @param $userId 发货代理用户ID
	 * @param $goodsId 商品ID
	 * @param $specId 规格ID
	 * @param $number 数量
	 * @return bool|string
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function changeStock($userId, $goodsId, $specId, $number) {
		$row = Db::name('agentStock')->alias('as')
			->join('goods g', 'as.goods_id = g.id', 'left')
			->join('goodsSpec s', 's.id = as.spec_id', 'left')
			->where(['as.user_id' => $userId, 'as.goods_id' => $goodsId, 'as.spec_id' => $specId])
			->field('as.id, g.name, s.name as spec_name, as.number')
			->find();
		if(!$row) {
			return '要发货的商品库存不存在';
		}
		
		if($row['number'] < $number) {
			return $row['name'].$row['spec_name'].'库存不足';
		}
		
		//减库存，加库存记录
		$descRes = Db::name('agentStock')
			->where(['id' => $row['id']])
			->setDec('number', $number);
		
		if(!$descRes) {
			return '减少库存出错';
		}
		
		$recordModel = new AgentStockRecord();
		$descRecordRes = $recordModel->addRecord($userId, $goodsId, $specId, $recordModel::TYPE_OUT, -$number, '发货');
		if(!$descRecordRes) {
			return '添加减少库存记录出错';
		}
		
		return true;
	}
	
	/**
	 * 更改下级代理库存
	 * @param $operateUserId
	 * @param $agentId
	 * @param $stockList
	 * @return bool
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function changeSonStockNumber($operateUserId, $agentId, $stockList)
	{
		$operateAgent = AgentShop::get(['user_id' => $operateUserId, 'status' => AgentShop::STATUS_Y]);
		if(!$operateAgent) {
			$this->errorMsg = '你不是代理';
			return false;
		}
		
		$agent = AgentShop::get([
			'role' => $operateAgent['role'] - 1,
			'status' => AgentShop::STATUS_Y,
			'id' => $agentId
		]);
		
		if(!$agent) {
			$this->errorMsg = '你不是该代理直属上级';
			return false;
		}
		
		$agentStock = Db::name('agentStock')
			->where(['agent_shop_id' => $agentId])
			->column('*', 'id');
		
		
		$recordModle = new AgentStockRecord();
		$stockModel = new AgentStock();
		
		$stockModel->startTrans();
		try {
			foreach ($stockList as $item) {
				if(isset($agentStock[$item['id']])) {
					//保存新库存
					$changeRes = Db::name('agentStock')
						->where(['id' => $item['id']])
						->update(['number' => $item['number'], 'update_time' => time()]);
					if(!$changeRes) {
						throw new Exception('更改库存数量出错');
					}
					
					//添加库存记录
					$stock = $agentStock[$item['id']];
					$changeNumber = $stock['number'] - $item['number'];
					
					$changeRecordRes = $recordModle->addRecord($agent['user_id'], $stock['goods_id'], $stock['spec_id'], $changeNumber > 0 ? $recordModle::TYPE_OUT : $recordModle::TYPE_IN, abs($changeNumber), '上级调整库存');
					if(!$changeRecordRes) {
						throw new Exception('添加库存记录出错');
					}
					
					//添加编辑代理库存
					$parentRes = $stockModel->add($operateAgent['user_id'], $operateAgent['id'], $stock['goods_id'], $stock['spec_id'], -1*$changeNumber);
					if(!$parentRes) {
						throw new Exception('更新操作代理库存数量出错');
					}
					
					//添加编辑代理库存记录
					$parentRecordRes = $recordModle->addRecord($operateAgent['user_id'], $stock['goods_id'], $stock['spec_id'], $changeNumber > 0 ? $recordModle::TYPE_IN : $recordModle::TYPE_OUT, abs($changeNumber), '调整下级库存');
					if(!$parentRecordRes) {
						throw new Exception('添加操作代理库存记录出错');
					}
				}
			}
			
			$stockModel->commit();
			return true;
		} catch (Exception $e) {
			$stockModel->rollback();
			$this->errorMsg = $e->getMessage();
			return false;
		}
		
	}
	
}
